package com.pinusmusic.web.serlvet;
/*
关于用户的系列操作
 */
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pinusmusic.domain.*;
import com.pinusmusic.service.MusicListService;
import com.pinusmusic.service.MusicService;
import com.pinusmusic.service.UserService;
import com.pinusmusic.service.impl.MusicListServiceImpl;
import com.pinusmusic.service.impl.MusicServiceImpl;
import com.pinusmusic.service.impl.UserServiceImpl;
import com.pinusmusic.util.UuidUtil;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.util.*;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    private UserService us = new UserServiceImpl();
    private MusicService ms=new MusicServiceImpl();
    private MusicListService mls = new MusicListServiceImpl();
    private List<Music> music;
    //用户登录功能
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("userName");
        String userpassword = req.getParameter("userPwd");
        boolean flag = us.findUserByUsernameAndUserpassword(username,userpassword);
        ResultInfo info = new ResultInfo();
        if (flag){
            //将用户的登录名存入到session
            req.getSession().setAttribute("username",username);
            List<User> user = us.findUserByName(username);
            req.getSession().setAttribute("user",user);
            req.getSession().setAttribute("uid",user.get(0).getUid());
            info.setFlag(true);
        }else {
            info.setFlag(false);
            info.setErrorMsg("用户名或密码错误！");
        }
        writeValue(resp,info);
    }
    //用户注册功能
    public void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = new User();
        Map<String, String[]> parameterMap = req.getParameterMap();
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        boolean flag = us.findUserByUsername(user.getUsername());
        ResultInfo info = new ResultInfo();
        if (!flag){
            user.setVipstatus("false");
            user.setCommentstatus("true");
            info.setFlag(true);
            us.insertUser(user);
        }else {
            info.setFlag(false);
            info.setErrorMsg("用户名已存在");
        }
        writeValue(resp,info);
    }
    //用户修改个人信息
    public void updateInformation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> parameterMap = req.getParameterMap();
        User user = new User();
        //登陆过后，session存有用户名，将其存入用户对象用于根据用户名修改用户相关信息
        user.setUsername((String)req.getSession().getAttribute("username"));
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        us.updateInformation(user);
        writeValue(resp,true);
    }
    //获取用户名
    public void getusername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String loginUser = (String)req.getSession().getAttribute("username");
        User user = new User();
        user.setUsername(loginUser);
        if (loginUser!=null){
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(user);
            resp.setContentType("application/json;charset-utf-8");
            resp.getWriter().write(json);
        }
    }
    //用户退出登录
    public void loginOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.销毁session域中的user
        req.getSession().invalidate();
        //2.跳转到新的页面 - login.html
        resp.sendRedirect(req.getContextPath() + "/userhtml/index.html");
    }
    //发送邮件
    public void sendEmail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String userEmail = req.getParameter("userEmail");
        //判断用户名和邮箱是否一致，一致发送邮件并返回true，不一致返回false
        Boolean flag = us.sendEmail(username, userEmail);
        //创建json结果
        ResultInfo info=new ResultInfo();
        info.setFlag(flag);
        if (flag){
            //将email存入session中，方便之后使用
            req.getSession().setAttribute("email",userEmail);
        }
        else {
            info.setErrorMsg("用户名与邮箱不匹对");
        }
        writeValue(resp,info);
    }
    public void findEmail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取session中的email，存入json用于前端显示
        String email = (String)req.getSession().getAttribute("email");
        ResultInfo info=new ResultInfo();
        if (email!=null){
            info.setFlag(true);
            info.setData(email);
        }
        else {
            info.setFlag(false);
        }
        writeValue(resp,info);
    }
    public void compareCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //输入的验证码
        String code = req.getParameter("code");
        String email = (String) req.getSession().getAttribute("email");
        //比较输入的验证码和数据库中用户对应的验证码，一致返回true，不一致返回false
        Boolean flag = us.compareCode(code, email);
        ResultInfo info=new ResultInfo();
        info.setFlag(flag);
        if(!flag){
            info.setErrorMsg("验证码错误");
        }
        writeValue(resp,info);
    }
    public void updatePassword(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String newPwd = req.getParameter("newPwd");
        String email = (String) req.getSession().getAttribute("email");
        Boolean flag = us.newPwd(newPwd, email);
        ResultInfo info=new ResultInfo();
        info.setFlag(flag);
        if (!flag){
            info.setErrorMsg("与旧密码相同");
        }
        writeValue(resp,info);
    }
    public void ListQuestion(HttpServletRequest req, HttpServletResponse resp)throws IOException{
        Map<Music, List<String>> map = ms.randMusic();
        for (Music m:map.keySet()){
            m.setMusicpath(URLDecoder.decode(m.getMusicpath(),"utf-8"));
        }
        Question question = new Question();
        music=new ArrayList<>();
        Map<Integer,List<String>> questions=new HashMap<>();
        int i=0;
        for (Music m:map.keySet()) {
            System.out.println(m.getMusicpath());
            music.add(m);
            questions.put(i,map.get(m));
            i++;
        }
        question.setMusic(music);
        question.setList(questions);
        writeValue(resp,question);
    }
    public void submit(HttpServletRequest req, HttpServletResponse resp)throws IOException{
        int score=0;
        for (int i = 0; i < 5; i++) {
            String option = req.getParameter("answer" + i + "");
            System.out.print(option);
            System.out.println(music.get(i));
            if (music.get(i).getMusicname().equals(option)){
                score+=20;
            }
        }
        if (score>=60){
            //发邮件
            User user = ((List<User>)req.getSession().getAttribute("user")).get(0);
            us.sendVipByEmail(user);
        }
        writeValue(resp,score);
    }
    public void active(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取激活码
        String vipcode = req.getParameter("vipcode");
        //2.调用service激活
        UserService us = new UserServiceImpl();
        boolean flag = us.active(vipcode);
        //3.判断flag 是否存在
        String msg = null;
        if(flag){
            //激活成功 - 重定向到新的html
            msg = "激活成功,请<a href='/music/userhtml/userlogin.html'>登录</a>";
            //resp.sendRedirect();
        }else {
            //激活失败 - 重定向到新的html
            msg = "激活失败";
            //resp.sendRedirect("新的html界面");
        }
        resp.getWriter().write(writeValueAsString(msg));
    }
    public void isLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Object username = req.getSession().getAttribute("username");
        boolean flag = false;
        if (username!=null){
            flag=true;
        }
        writeValue(resp,flag);
    }
    public void isVip(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = ((List<User>)req.getSession().getAttribute("user")).get(0);
        ResultInfo info = new ResultInfo();
        if (user==null){
            info.setFlag(false);
            info.setErrorMsg("试听已结束，完整版请成为VIP");
        }else {
            if (user.getVipstatus().equals("true")){
                info.setFlag(true);
            }else {
                info.setFlag(false);
                info.setErrorMsg("试听已结束，完整版请成为VIP");
            }
        }
        writeValue(resp,info);
    }
    //用户的模模糊查询
    public void findUsersByName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        System.out.println("user获取的name:"+name);
        //获取前端得到的当前页面
        String curStr = request.getParameter("currentPage");
        //一开始就为第一页
        if (curStr==null || curStr.equals("") || curStr.equals("0")) curStr="1";
        int currentPage = Integer.parseInt(curStr);
        //设置每次查询五条;
        int rows = 5;
        PageBean<User> pageBean = us.findUsersByName(currentPage, rows, name);
        LinkedHashMap<String,Integer> map = new LinkedHashMap<>();
        List<User> list = pageBean.getList();
        if (list!=null){
            for (int i = 0; i < list.size(); i++) {
                int count = mls.getCountByUid(list.get(i).getUid());
                map.put(list.get(i).getUsername(),count);
            }
        }
        pageBean.setMap(map);
        System.out.println("findUsersByName的结果:"+pageBean);
        writeValue(response,pageBean);
    }
    public void getMusicList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<User> list = (List<User>) req.getSession().getAttribute("user");
        User user = list.get(0);
        List<MusicList> creationlist = mls.findCreationlistByUid(user.getUid());
        System.out.println(creationlist);
        writeValue(resp,creationlist);
    }
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String mid = req.getParameter("mid");
        String mlid = req.getParameter("mlid");
        System.out.println("获取到的mid:"+mid+",获取到的mlid:"+mlid);
        mls.addMusic(Integer.parseInt(mlid),Integer.parseInt(mid));
    }

    public void findUserByUid(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user=us.findUserByUid(Integer.parseInt(req.getParameter("uid")));
        System.out.println("查到的user为："+user);
        writeValue(resp,user);
    }
}
